/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT,
 * THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package lineage.core.handler;

import java.io.InputStream;

import lineage.core.L1GameClient;
import lineage.util.StreamUtil;
import lineage.util.Util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 读处理器,即具体的读客户端的信息由它完成.
 * 如果服务器要回应该客户端,需要回调写处理器.
 * 
 * @version 2014年3月9日下午3:35:07
 * @author jrwz
 */
public final class L1ReadHandler extends L1AbstractHandler {
    private static final Logger LOG = LoggerFactory.getLogger(L1ReadHandler.class);

    /** 测试用数组,用来排除指定封包的显示. */
    private static final int[] TEST_ARRAY = new int[] { 24, 66, 87, 102 };

    /**
     * 读处理器.
     * 
     * @param client
     *            - 客户端
     * @param in
     *            - 输入流
     */
    public L1ReadHandler(final L1GameClient client, final InputStream in) {
        this.client = client;
        this.in = in;
        keys = client.getKeys();
        pah = new L1PacketAcceptHandler(client, 2);
    }

    @Override
    public void execute(final byte[] data) {
        // cph.execute(data); // 移交至封包处理程序 直接处理
        pah.executeQueue(data); // 加入队列 稍后处理

        final int opcode = data[0] & 0xFF;

        boolean flag = true;
        for (int i : TEST_ARRAY) {
            if (opcode == i) { // 排除指定封包显示
                flag = false;
            }
        }
        if (flag) {
            Util.message(Util.SYSTEM_MESSAGE, "客户端封包：" + opcode);
        }
    }

    @Override
    public byte[] toDecrypt() throws Exception {
        try {
            final int hiByte = in.read();
            final int loByte = in.read();

            if ((loByte < 0) || (hiByte < 0)) {
                throw new RuntimeException();
            }

            final int dataLength = ((loByte << 8) + hiByte) - 2;

            if ((dataLength <= 0) || (dataLength > 65533)) {
                throw new RuntimeException();
            }

            final byte data[] = new byte[dataLength];

            int readSize = 0;

            for (int i = 0; (i != -1) && (readSize < dataLength); readSize += i) {
                i = in.read(data, readSize, dataLength - readSize);
            }

            if (readSize != dataLength) {
                throw new RuntimeException();
            }

            return keys.decrypt(data);
        } catch (final Exception e) {
            // LOG.error(e.getLocalizedMessage(), e);
            throw e;
        }
    }

    @Override
    public void close() {
        try {
            StreamUtil.close(in);
        } catch (final Exception e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
}